package com.springcloudemo.ms;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.cloud.gateway.filter.factory.DedupeResponseHeaderGatewayFilterFactory;
import org.springframework.cloud.gateway.filter.factory.RemoveResponseHeaderGatewayFilterFactory;
import org.springframework.cloud.gateway.filter.factory.StripPrefixGatewayFilterFactory;
import org.springframework.cloud.gateway.support.GatewayToStringStyler;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author Yangdw
 * @date 2025-08-19
 * @description:
 */
@Component
public class CostGatewayFilterFactory  extends AbstractGatewayFilterFactory<String> {

    public CostGatewayFilterFactory() {
        super(String.class);
    }
    @Override
    public GatewayFilter apply(String config) {
        return new GatewayFilter() {
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                if ("off".equals(config)){
                    return chain.filter(exchange);
                }

                //处理请求之前可以干点事情
                exchange.getAttributes().put("Start_Time",System.currentTimeMillis());
                return chain.filter(exchange).then(Mono.fromRunnable(() -> {
                    //处理请求之后也可以干点事情
                    Long start_time = exchange.getAttribute("Start_Time");

                    if (start_time != null){
                        long endTime = System.currentTimeMillis();
                        long cost = endTime - start_time;
                        System.out.println("请求地址: "+exchange.getRequest().getURI()
                        + " 耗时为: "+cost+ " 毫秒");
                    }
                }));
            }

        };
    }
}
